package com.nstar.sinaweibo.controller
{
	import com.nstar.base.util.DateUtils;
	import com.nstar.base.util.Logger;
	import com.nstar.sinaweibo.model.FaceLoader;
	import com.nstar.sinaweibo.model.HolidayLoader;
	import com.nstar.sinaweibo.model.HolidayVO;
	import com.nstar.sinaweibo.model.MainData;
	import com.nstar.sinaweibo.model.ThemeLoader;
	import com.nstar.sinaweibo.model.Utils;
	import com.sina.microblog.MicroBlog;
	import com.sina.microblog.data.MicroBlogComment;
	import com.sina.microblog.data.MicroBlogDirectMessage;
	import com.sina.microblog.data.MicroBlogRateLimit;
	import com.sina.microblog.data.MicroBlogRelationshipDescriptor;
	import com.sina.microblog.data.MicroBlogStatus;
	import com.sina.microblog.data.MicroBlogUser;
	import com.sina.microblog.data.MicroBlogUsersRelationship;
	import com.sina.microblog.events.MicroBlogErrorEvent;
	import com.sina.microblog.events.MicroBlogEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Point;
	import flash.net.SharedObject;
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	
	public class MainController extends EventDispatcher
	{
		//使用到名字的地方：标题、版本更新历史、关于窗口
		public static const APP_NAME		:String = "开心果";
		
		public static const STATUS			:int = 0;
		public static const MENTIONS		:int = 1;
		public static const COMMENT			:int = 2;
		public static const DIRECT_MESSAGE	:int = 3;
		public static const FOLLOWERS		:int = 4;
		public static const USER_TIMELINE	:int = 5;
		
		public static const CONFIG_URL:String = "assets/sinaweibo_faces.xml";
		public static const THEME_URL:String = "http://mistachio.googlecode.com/files/sinaweibo_themes.xml";
		public static const HOLIDAY_URL:String = "http://mistachio.googlecode.com/files/sinaweibo_holiday.xml";//"app:/assets/sinaweibo_holiday.xml";
		public static const APP_URL:String = "http://t.sina.com.cn/app/detail/4HdF6l";
		public static const RECOMMEND:String = "欢迎你们也来试试新浪微博客户端【"+APP_NAME+"】哦~ 到这里来下载："+APP_URL;
		//选项设置保存的位置
		public static const SHARED_OBJECT_URL:String = "Main/sinaweibo/options";
		
		public static const RESTORE_REFRESH_INTERVAL:Number = 1;//分钟，恢复自动刷新的倒计时
		public static const SECOND:Number = 1000;//一秒钟,1000毫秒
		public static const MINUTE:Number = 60*SECOND;//一分钟
		
		
		public var app:SinaWeibo;
		
		public var microBlogAPI:MicroBlog ;
		private var _mainData:MainData = new MainData();
		
		private var _isPaging:Boolean = false;//是否在分页取数据
		public var refreshPaused:Boolean = false;//暂停自动刷新，在分页时需要暂停自动刷新，以让用户能浏览翻页的消息
		//private var timerAutoRefresh:Timer;//恢复自动刷新的计时器
		
		public var faceLoader:FaceLoader;
		public var themeLoader:ThemeLoader;
		public var holidaLoader:HolidayLoader;
		
		private var sharedObject:SharedObject;//共享数据保存
		
		private var logger:Logger = Logger.getInstance(this);
		
		public var isMine:Boolean = false;//是否加载自己的信息，自动刷新时检查新粉丝
		
		public static var debugging:Boolean = false;//调试状态
		
		public function MainController()
		{
			logger.debug("欢迎使用新浪微博桌面客户端~"); 
			
			microBlogAPI = Utils.getMicroBlog();
			
			microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_FRIENDS_INFO_ERROR, onErrorHandler);
			microBlogAPI.addEventListener(MicroBlogEvent.VERIFY_CREDENTIALS_RESULT, 	onVerifyResult);
			microBlogAPI.addEventListener(MicroBlogErrorEvent.VERIFY_CREDENTIALS_ERROR,onErrorHandler);
			microBlogAPI.addEventListener(MicroBlogEvent.GET_RATE_LIMIT_STATUS_RESULT,	onGetRateLimitStatusResult);
		//Status
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_FRIENDS_TIMELINE_RESULT, 	onLoadFriendsTimeLineResult);
			microBlogAPI.addEventListener(MicroBlogEvent.UPDATE_STATUS_RESULT, 			onUpdateStatusResult);
			microBlogAPI.addEventListener(MicroBlogEvent.REPOST_STATUS_RESULT, 			onRepostStatusResult);
			microBlogAPI.addEventListener(MicroBlogEvent.COMMENT_STATUS_RESULT, 		onCommentStatusResult);
			microBlogAPI.addEventListener(MicroBlogEvent.REPLY_STATUS_RESULT, 			onReplyStatusResult);
			microBlogAPI.addEventListener(MicroBlogEvent.DELETE_STATUS_RESULT,			onDeleteStatusResult);
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_STATUS_COUNTS_RESULT,		onLoadStatusCountsResult);
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_PUBLIC_TIMELINE_RESULT,	onLoadPublicTimeLineResult);
		//User
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_FRIENDS_INFO_RESULT, 		onLoadFriendsResult);
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_FOLLOWERS_INFO_RESULT, 	onLoadFollowersResult);
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_USER_TIMELINE_RESULT, 	onLoadUserTimeLineResult);
			microBlogAPI.addEventListener(MicroBlogEvent.FOLLOW_RESULT,					onFollowResult);
			microBlogAPI.addEventListener(MicroBlogEvent.CANCEL_FOLLOWING_RESULT, 		onCancelFollowingResult);
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_FRIENDS_ID_LIST_RESULT,	onLoadFriendsIdListResult);
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_USER_INFO_RESULT,			onLoadUserInfoResult);
			
		//Comment
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_COMMENTS_TIMELINE_RESULT,	onLoadCommentsTimelineResult);
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_MY_COMMENTS_RESULT, 		onLoadMyCommentsResult);
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_COMMENTS_RESULT,			onLoadStatusCommentsResult);
			microBlogAPI.addEventListener(MicroBlogEvent.DELETE_COMMENT_RESULT, 		onDeleteCommentResult);
		//DirectMessage
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_DIRECT_MESSAGES_RECEIVED_RESULT, 	onLoadReceivedDirectMsgResult);
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_DIRECT_MESSAGES_SENT_RESULT, 		onLoadSentDirectMsgResult);
			microBlogAPI.addEventListener(MicroBlogEvent.SEND_DIRECT_MESSAGE_RESULT, 	onSendDirectMsgResult);
			microBlogAPI.addEventListener(MicroBlogEvent.DELETE_DIRECT_MESSAGE_RESULT, 	onDeleteDirectMsgResult);
		//Favorite			
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_FAVORITE_LIST_RESULT, 	onLoadFavoritesResult);
			microBlogAPI.addEventListener(MicroBlogEvent.ADD_TO_FAVORITES_RESULT,		onAddToFavoritesResult);
			microBlogAPI.addEventListener(MicroBlogEvent.REMOVE_FROM_FAVORITES_RESULT, 	onRemoveFromFavoritesResult);
			
		//Mentions
			microBlogAPI.addEventListener(MicroBlogEvent.LOAD_MENSIONS_RESULT, 			onMensionsResult);
			
			microBlogAPI.addEventListener(MicroBlogEvent.CHECK_IS_FOLLOWING_RESULT,		onCheckIsFollowingResult);
			
		//Error
			microBlogAPI.addEventListener(MicroBlogErrorEvent.UPDATE_STATUS_ERROR, 			onErrorHandler);
			microBlogAPI.addEventListener(MicroBlogErrorEvent.REPOST_STATUS_ERROR, 			onErrorHandler);
			microBlogAPI.addEventListener(MicroBlogErrorEvent.COMMENT_STATUS_ERROR,			onErrorHandler);
			microBlogAPI.addEventListener(MicroBlogErrorEvent.ADD_TO_FAVORITES_ERROR,		onErrorHandler);
			microBlogAPI.addEventListener(MicroBlogErrorEvent.REMOVE_FROM_FAVORITES_ERROR,	onErrorHandler);
			microBlogAPI.addEventListener(MicroBlogErrorEvent.FOLLOW_ERROR,					onErrorHandler);
			
			//获取服务器时间，通过获取最新的微博来取服务器时间
			this.loadPublicTimeline();

			//开始加载一些配置文件
			load();
			
		}
		
		//加载一些配置
		public function load():void{
		//load Encrypted User info
			_mainData.loginData.loadUserPassword();
		//load options config
			_mainData.loadEncryptedOptions();

			//加载表情
			faceLoader = new FaceLoader(CONFIG_URL);
			faceLoader.addEventListener(Event.COMPLETE,facesCompleteHandler);
			
			//加载主题配置
			themeLoader = new ThemeLoader(THEME_URL);
			themeLoader.addEventListener(Event.COMPLETE,themesCompleteHandler);
			
			//获取共享数据
			sharedObject = SharedObject.getLocal(SHARED_OBJECT_URL);
		}
		
		//获取表情
		private function facesCompleteHandler(event:Event):void{
			_mainData.faces = faceLoader.faceList;
		}
		
		//获取主题
		private function themesCompleteHandler(event:Event):void{
			_mainData.themes = themeLoader.themes;
			this.dispatchEvent(new ClientEvent(ClientEvent.THEMES_DOWNLOAD_COMPLETE));
		}
		
		//异常处理
		private function onErrorHandler(event:MicroBlogErrorEvent):void
		{
			trace(event.message);
			switch(event.type){
				case MicroBlogErrorEvent.VERIFY_CREDENTIALS_ERROR://登录失败
					dispatchEvent(new ClientEvent(ClientEvent.LOGIN_FAILED));
					break;
				default:
					dispatchEvent(new ClientEvent(event.type));
					break;
			}
		}
		
		//用户登录，普通方式
		public function login(userName:String, password:String, save:Boolean,autoLogin:Boolean):void
		{
			logger.debug("logining...");
			microBlogAPI.accessTokenKey = "";
			microBlogAPI.accessTokenSecrect = "";
			microBlogAPI.pin = "";
			
			_mainData.loginData.username = userName;
			_mainData.loginData.password = password;
			_mainData.loginData.savePassword = save;
			_mainData.loginData.autoLogin = autoLogin;
			microBlogAPI.login(userName, password);
		}
		
		//Oauth方式授权登录
		public function oauthLoginRequest():void{
			logger.debug("logining in Oauth ...");
			microBlogAPI.consumerKey = Utils.APP_ID;
			microBlogAPI.consumerSecret = Utils.APP_SECRET;			
			microBlogAPI.login();
		}
		
		//pin登录
		public function oauthLogin(pin:String):void{
			microBlogAPI.pin = pin;
		}
		
	//Status		
		public function loadPublicTimeline():void{
			microBlogAPI.loadPublicTimeline();
		}
		
		public function loadFriendsTimeline(page:uint=1):void
		{
			microBlogAPI.loadFriendsTimeline(0,0,0,page);
		}
		public function publishStatus(text:String, image:ByteArray=null, imageName:String=null):void
		{
			microBlogAPI.updateStatus(text, imageName, image);
		}
		public function repostStatus(originalStatus:MicroBlogStatus,text:String):void
		{
			microBlogAPI.repostStatus(originalStatus.id,text);
		}
		public function commentStatus(originalStatus:MicroBlogStatus,text:String):void
		{
			microBlogAPI.commentStatus(originalStatus.id, text);
		}
		public function replyComment(originalComment:MicroBlogComment, text:String):void
		{
			microBlogAPI.replyStatus(originalComment.status.id, text, originalComment.id);
		}
		public function removeStatus(status:MicroBlogStatus):void
		{
			microBlogAPI.deleteStatus(status.id);
		}
		
		public function loadStatusCounts(status:Array):void
		{
			//先取微博的ID，包括转发的微博
			var ids:Array = new Array();
			for each(var sts:MicroBlogStatus in status){
				ids.push(sts.id.toString());
				//如果有转发的微博
				if(sts.repost){
					ids.push(sts.repost.id.toString());
				}
			}
			//开始获取
			microBlogAPI.loadStatusCounts(ids);
		}
	//User
		public function loadUserFriends(user:MicroBlogUser,cursor:Number = -1):void
		{
			microBlogAPI.loadFriendsInfo(null, user.id,null,cursor);
		}
		public function loadUserFollowers(user:MicroBlogUser,cursor:Number = -1):void
		{
			microBlogAPI.loadFollowersInfo(null, user.id,null,cursor);
		}
		public function loadUserStatus(user:MicroBlogUser,count:uint = 0,page:uint = 1):void
		{
			microBlogAPI.loadUserTimeline(null, user.id, null,0,0,count,page);
		}
		public function follow(user:MicroBlogUser):void
		{
			microBlogAPI.follow(user.name, user.id, user.screenName);
		}

		public function follow2(id:Number=0,screenName:String=null):void
		{
			microBlogAPI.follow(null, id, screenName);
		}
		
		public function cancelFollow(user:MicroBlogUser):void
		{
			microBlogAPI.cancelFollowing(user.name, user.id, user.screenName);
		}
		public function cancelFans(user:MicroBlogUser):void
		{
		}
		
		public function loadUserInfo(userId:Number = 0,screenName:String = null,isMine:Boolean = false):void{
			this.isMine = isMine;
			microBlogAPI.loadUserInfo(null,userId,screenName);
		}
		
		public function loadFriendsIDList(user:MicroBlogUser):void
		{
			microBlogAPI.loadFriendsIDList(null,user.id);
		}
	//Comment
		public function loadCommentsTimeline(count:uint = 0,page:uint = 1):void
		{
			microBlogAPI.loadCommentsTimeline(0,0,count,page);
		}
		public function loadMyComments():void
		{
			microBlogAPI.loadMyComments();
		}
		public function loadStatusComments(status:MicroBlogStatus,page:uint=1):void
		{
			microBlogAPI.loadCommentList(status.id,0,page);
		}
		public function removeComment(comment:MicroBlogComment):void
		{
			microBlogAPI.deleteComment(comment.id);
		}
		
	//DirectMessage
		public function loadReceivedDirectMsg(count:uint = 1000,page:uint = 1):void
		{
			microBlogAPI.loadDirectMessagesReceived(0,0,count,page);
		}
		public function loadSentDirectMsg(count:uint = 1000,page:uint = 1):void
		{
			microBlogAPI.loadDirectMessagesSent(0,0,count,page);
		}
		public function sendDirectMsg(reciever:MicroBlogUser, msg:String):void
		{
			microBlogAPI.sendDirectMessage(String(reciever.id), msg);
		}
		public function removeDirectMsg(directMsg:MicroBlogDirectMessage):void
		{
			microBlogAPI.deleteDirectMessage(directMsg.id);
		}
		
	//Favorite
		public function loadFavorites(page:uint=0):void
		{
			microBlogAPI.loadFavoriteList(page);
		}
		public function favoriteStatus(status:MicroBlogStatus):void
		{
			microBlogAPI.addToFavorites(status.id);
		}
		public function cancelFavoriteStatus(status:MicroBlogStatus):void
		{
			microBlogAPI.removeFromFavorites(status.id);
		}
		
	//Mentions
		public function loadMentions(count:uint=0,page:uint=1):void
		{
			microBlogAPI.loadMentions(0,0,count,page);
		}
		
	//CallBack，登录成功
		private function onVerifyResult(event:MicroBlogEvent):void
		{
			logger.debug("login successful!");
			_mainData.logined = true;//已经登录标志
			_mainData.currentUser = event.result as MicroBlogUser;
			_mainData.shownUser = _mainData.currentUser;
			
			//保存用户名称和密码，并加载该用户对应的相关信息，用户在登录界面可能重新使用了其它帐号来登录
			_mainData.loginData.saveUserPassword();
			_mainData.loginData.load();//load again
			
			//检查新粉丝
			var newFollowersCount:int = _mainData.currentUser.followersCount - _mainData.loginData.followers;
			if(newFollowersCount>0 && _mainData.loginData.followers>0){
				_mainData.newFollwersCount = newFollowersCount;
			}else{
				_mainData.loginData.followers = _mainData.currentUser.followersCount;
			}
			
			//保存用户其它信息
			_mainData.loginData.save();
			//获取当前API调用数限制
			microBlogAPI.getRateLimitInfo();
			dispatchEvent(new ClientEvent(ClientEvent.LOGIN_SUCCESS));
			
			//加载默认关注的微博
			loadFriendsTimeline();
			//首次运行时，发布一条推荐微博，根据微博规范，不可以自动发微博
			/* if(_mainData.optionsVO.firstRun){
				trace("这是第一次使用~发布一条首次使用客户端的微博");
				PopUpView.show("欢迎使用微博客户端~这是您第一次使用Sina Weibo，这里是使用向导~",null,"欢迎使用");
				publishStatus("欢迎使用微博客户端 Sina Weibo~");
			}else{
				//加载默认关注的微博
				loadFriendsTimeline();
			} */
		}
		
		private function onGetRateLimitStatusResult(event:MicroBlogEvent):void{
			var limit:MicroBlogRateLimit = MicroBlogRateLimit(event.result);
			logger.debug("hourlyLimit="+limit.hourlyLimit+",remainingHits="+limit.remainingHits);
		}
		
	//Login Error
		private function onLoginErrorHandler(event:MicroBlogErrorEvent):void{
			logger.debug("login error >>>"+event.message);
			mainData.loginData.logined = false;
		}
		///////////////////////////////////////////////////////////////////////////
	//Status
		private function onLoadFriendsTimeLineResult(event:MicroBlogEvent):void
		{
			mainData.friendTimeLineList = new ArrayCollection(event.result as Array);
			//检查新微博
			var news:ArrayCollection = filterMessages(mainData.friendTimeLineList,STATUS);
			dispatchEvent(new ClientEvent(ClientEvent.LOAD_FRIENDS_TIMELINE_SUCCESS,false,news));
			//获取微博的评论、转发数
			loadStatusCounts(event.result as Array);
		}
		private function onUpdateStatusResult(event:MicroBlogEvent):void
		{
			//第一次发布的自动推荐微博不通知
			if(_mainData.optionsVO.firstRun){
				trace("update first run to false");
				_mainData.setFirstRun(false);
				trace("begin loadFriendsTimeline...");
				this.loadFriendsTimeline();
			}else{
				//保存最新的ID
				mainData.lastFriendTimeLineID = MicroBlogStatus(event.result).id;
				dispatchEvent(new ClientEvent(ClientEvent.UPDATE_STATUS_SUCCESS,false,event.result));
			}
			
		}
		private function onRepostStatusResult(event:MicroBlogEvent):void
		{
			//保存最新的ID
			mainData.lastFriendTimeLineID = MicroBlogStatus(event.result).id;
			dispatchEvent(new ClientEvent(ClientEvent.REPOST_STATUS_SUCCESS,false,event.result));
		}
		
		private function onCommentStatusResult(event:MicroBlogEvent):void
		{
			dispatchEvent(new ClientEvent(ClientEvent.COMMENT_STATUS_SUCCESS));
		}
		private function onReplyStatusResult(event:MicroBlogEvent):void
		{
			dispatchEvent(new ClientEvent(ClientEvent.REPLY_COMMENT_SUCCESS));
		}
		private function onDeleteStatusResult(event:MicroBlogEvent):void
		{
			dispatchEvent(new ClientEvent(ClientEvent.DELETE_STATUS_SUCCESS,false,event.result));
		}
		
		private function onLoadStatusCountsResult(event:MicroBlogEvent):void
		{
			mainData.statusCounts = new ArrayCollection(event.result as Array);
			dispatchEvent(new ClientEvent(ClientEvent.LOAD_STATUS_COUNTS_SUCCESS,false,mainData.statusCounts));
		}
		
		//获取公共微博
		private function onLoadPublicTimeLineResult(event:MicroBlogEvent):void{
			var list:ArrayCollection = new ArrayCollection(event.result as Array);
			if(list && list.length>0){
				//通过获取最新微博的方式来取得最新的服务器日期
				var status:MicroBlogStatus = list.getItemAt(0) as MicroBlogStatus;
				mainData.today = status.createdAt;
				
				//加载一些特殊日期信息，处理日期信息
				holidaLoader = new HolidayLoader(HOLIDAY_URL);
				holidaLoader.addEventListener(Event.COMPLETE,holidaysCompleteHandler);
				
				logger.debug("Today is : "+DateUtils.format(mainData.today,"YYYY-MM-DD"));
			}
		}
		
		//日期加载完成
		private function holidaysCompleteHandler(event:Event):void{
			//_mainData.holidays = holidaLoader.holidays;
			var day:HolidayVO = holidaLoader.getDay(_mainData.today);
			//取默认的LOGO，默认的LOGO也有可能没有设置
			if(day==null){
				day = holidaLoader.defaultLogo;
			}
			
			_mainData.holiday = day;
			this.dispatchEvent(new ClientEvent(ClientEvent.HOLIDAY,false,day));
		}
		
		
	//User
		private function onLoadFriendsResult(event:MicroBlogEvent):void
		{
			mainData.friendsList = new ArrayCollection(event.result as Array);
			dispatchEvent(new ClientEvent(ClientEvent.LOAD_FRIENDS_INFO_SUCCESS,
				false,mainData.friendsList));
		}
		private function onLoadFollowersResult(event:MicroBlogEvent):void
		{
			mainData.followersList = new ArrayCollection(event.result as Array);
			dispatchEvent(new ClientEvent(ClientEvent.LOAD_FOLLOWERS_INFO_SUCCESS,
				false,mainData.followersList));
		}
		private function onLoadUserTimeLineResult(event:MicroBlogEvent):void
		{
			mainData.userTimeLineList = new ArrayCollection(event.result as Array);
			dispatchEvent(new ClientEvent(ClientEvent.LOAD_USER_TIMELINE_SUCCESS,
				false,mainData.userTimeLineList));
			//获取微博的评论、转发数
			loadStatusCounts(event.result as Array);
		}
		private function onFollowResult(event:MicroBlogEvent):void
		{
			dispatchEvent(new ClientEvent(ClientEvent.FOLLOW_SUCCESS));
		}
		private function onCancelFollowingResult(event:MicroBlogEvent):void
		{
			dispatchEvent(new ClientEvent(ClientEvent.CANCEL_FOLLOW_SUCCESS));
		}
		
		
		private function onLoadFriendsIdListResult(event:MicroBlogEvent):void
		{
			var ids:Array = event.result as Array;
			for each(var id:Number in ids){
				microBlogAPI.loadUserInfo(null,id);
			}
		}
		
		private function onLoadUserInfoResult(event:MicroBlogEvent):void{
			var user:MicroBlogUser = event.result as MicroBlogUser;
			if(isMine){
				//检查是否有新粉丝
				var newFollowers:int = user.followersCount - mainData.loginData.followers;
				if(newFollowers > 0){
					dispatchEvent(new ClientEvent(ClientEvent.NEW_FOLLOWERS,false,newFollowers));
				}
				//标志还原
				isMine = false;				
			}else{
				dispatchEvent(new ClientEvent(ClientEvent.LOAD_USER_INFO_SUCCESS,false,user));
			}
		}		
		
	//Comment
		private function onLoadCommentsTimelineResult(event:MicroBlogEvent):void
		{
			mainData.commentsList = new ArrayCollection(event.result as Array);
			//检查新评论
			var news:ArrayCollection = filterMessages(mainData.commentsList,COMMENT);
			dispatchEvent(new ClientEvent(ClientEvent.LOAD_COMMENTS_TIMELINE_SUCCESS,false,news));
		}
		
		private function onLoadMyCommentsResult(event:MicroBlogEvent):void
		{
			mainData.commentsList = new ArrayCollection(event.result as Array);
		}
		
		//加载指定微博的评论
		private function onLoadStatusCommentsResult(event:MicroBlogEvent):void
		{
			var list:ArrayCollection = new ArrayCollection(event.result as Array);
			dispatchEvent(new ClientEvent(ClientEvent.LOAD_STATUS_COMMENTS_SUCCESS,false,list));
		}
		private function onDeleteCommentResult(event:MicroBlogEvent):void
		{
			dispatchEvent(new ClientEvent(ClientEvent.DELETE_COMMENT_SUCCESS,false,
				event.result as MicroBlogComment));
		}
		
	//DirectMessage
		private function onLoadReceivedDirectMsgResult(event:MicroBlogEvent):void
		{
			mainData.directMsgReceivedList = new ArrayCollection(event.result as Array);
			//检查新私信
			var news:ArrayCollection = filterMessages(mainData.directMsgReceivedList,DIRECT_MESSAGE);
			//合并私信
			var all:ArrayCollection = new ArrayCollection(mainData.directMsgList.toArray().concat(news.toArray()));
			dispatchEvent(new ClientEvent(ClientEvent.LOAD_DIRECT_MESSAGES_RECEIVED_SUCCESS,false,all));
		}		
		
		private function onLoadSentDirectMsgResult(event:MicroBlogEvent):void
		{
			mainData.directMsgSentList = new ArrayCollection(event.result as Array);
			//发出的私信不作为新消息发送
			dispatchEvent(new ClientEvent(ClientEvent.LOAD_DIRECT_MESSAGES_SENT_SUCCESS,false,new ArrayCollection()));
		}
		
		private function onSendDirectMsgResult(event:MicroBlogEvent):void
		{
			dispatchEvent(new ClientEvent(ClientEvent.SEND_MSG_SUCCESS,false,event.result));
		}
		private function onDeleteDirectMsgResult(event:MicroBlogEvent):void
		{
			dispatchEvent(new ClientEvent(ClientEvent.DELETE_MSG_SUCCESS,false,event.result));
		}
	//Favorite
		private function onLoadFavoritesResult(event:MicroBlogEvent):void
		{
			mainData.favoritesList = new ArrayCollection(event.result as Array);
			dispatchEvent(new ClientEvent(ClientEvent.LOAD_FAVORITE_LIST_SUCCESS,
				false,mainData.favoritesList));	
			//获取微博的评论、转发数
			loadStatusCounts(event.result as Array);

		}
		private function onAddToFavoritesResult(event:MicroBlogEvent):void
		{
			dispatchEvent(new ClientEvent(ClientEvent.ADD_TO_FAVORITE_SUCCESS));
		}
		private function onRemoveFromFavoritesResult(event:MicroBlogEvent):void
		{
			dispatchEvent(new ClientEvent(ClientEvent.CANCEL_FAVORITE_SUCCESS,false,event.result));
		}
	//Mentions
		private function onMensionsResult(event:MicroBlogEvent):void
		{
			mainData.metionsList = new ArrayCollection(event.result as Array);
			//检查新微博
			var news:ArrayCollection = filterMessages(mainData.metionsList,MENTIONS);
			dispatchEvent(new ClientEvent(ClientEvent.LOAD_MENTIONS_SUCCESS,false,news));
			//获取微博的评论、转发数
			loadStatusCounts(event.result as Array);
		}
	//Relationship
		private function onCheckIsFollowingResult(event:MicroBlogEvent):void{
			var relation:MicroBlogUsersRelationship = event.result as MicroBlogUsersRelationship;
			var src:MicroBlogRelationshipDescriptor = relation.source;
			var dest:MicroBlogRelationshipDescriptor = relation.target;
			trace("src>>"+src.screenName+",isFollowedBy="+src.isFollowedBy+",isFollowingMe="+src.isFollowingMe);
			trace("dest>>"+dest.screenName+",isFollowedBy="+dest.isFollowedBy+",isFollowingMe="+dest.isFollowingMe);
			dispatchEvent(new ClientEvent(ClientEvent.CHECK_IS_FOLLOWING_SUCCESS,false,dest));
		}
		
		
		//过滤出新消息，对于是自己发布的，则不归为新消息里
		private function filterMessages(result:ArrayCollection,msgType:int):ArrayCollection{
			trace("_isPaging="+_isPaging);
			
			var list:ArrayCollection = new ArrayCollection();
			switch(msgType){
				case STATUS:
					list = getNewList(result,mainData.lastFriendTimeLineID);
					//新消息数
					if(_isPaging == false){
						mainData.newFriendTimeLimeCount += getNewCount(list,mainData.lastFriendTimeLineID);
						//保存最后ID
						mainData.lastFriendTimeLineID = getLastID(result);
					}
					trace("newFriendTimeLimeCount="+mainData.newFriendTimeLimeCount+",lastFriendTimeLineID="+mainData.lastFriendTimeLineID);
					return _isPaging?result:list;//如果是分页，则直接返回原结果
				case MENTIONS:
					list = getNewList(result,mainData.lastMentionsID);
					//新消息数，消息数累加，在阅读后自减
					if(_isPaging == false){
						mainData.newMentionsCount += getNewCount(list,mainData.lastMentionsID);
						//保存最后ID
						mainData.lastMentionsID = getLastID(result);
					}
					trace("newMentionsCount="+mainData.newFriendTimeLimeCount+",lastMentionsID="+mainData.lastMentionsID);
					return _isPaging?result:list;//如果是分页，则直接返回原结果
				case COMMENT:
					list = getNewList(result,mainData.lastCommentID);
					//新消息数
					if(_isPaging == false){
						mainData.newCommentCount += getNewCount(list,mainData.lastCommentID);
						//保存最后ID
						mainData.lastCommentID = getLastID(result);
					}
					trace("newCommentCount="+mainData.newCommentCount+",lastCommentID="+mainData.lastCommentID);
					return _isPaging?result:list;//如果是分页，则直接返回原结果
				case DIRECT_MESSAGE:
					list = getNewList(result,mainData.lastDirectMessageID);
					//新消息数
					if(_isPaging == false){
						mainData.newDirectMessageCount += getNewCount(list,mainData.lastDirectMessageID);
						//保存最后ID
						mainData.lastDirectMessageID = getLastID(result);
					}
					trace("newDirectMessageCount="+mainData.newDirectMessageCount+",lastDirectMessageID="+mainData.lastDirectMessageID);
					return _isPaging?result:list;//如果是分页，则直接返回原结果
				case FOLLOWERS:
					return new ArrayCollection();
			}
			//没传消息类型时返回空列表
			return new ArrayCollection();
		}
		
		//获取最新列表
		private function getNewList(result:ArrayCollection,lastID:Number){
			var list:ArrayCollection = new ArrayCollection();
			//如果lastID为0，则直接返回原列表，表示是第一次取数据
			if(lastID == 0) return result;
			//比较ID
			for each(var item:Object in result){
				if(item.id>lastID){
					list.addItem(item);
				}
			}
			
			//如果有消息，在最后插入一条分隔符
			/* if(list.length>0){
				var sepVO:SeparatorVO = new SeparatorVO();
				list.addItem(sepVO);
			} */
			
			return list;
		}
		
		//获取新消息数
		private function getNewCount(list:ArrayCollection,lastID:Number):int{
			//判断是否为自己的消息
			var notMine:Boolean = isNotMine(list);
			if(notMine){
				return lastID==0?0:list.length;
			}else{
				return 0;//如果是自己的消息，则返回0
			}
			
		}
		
		//获取最后一条消息的ID
		private function getLastID(list:ArrayCollection):Number{
			if(list && list.length>0){
				return Number(list.getItemAt(0).id);
			}else{
				return 0;
			}
		}
		
		//检查是否都为自己的消息,返回true为不是自己的，false为是自己的
		private function isNotMine(list:ArrayCollection):Boolean{
			for each(var item:Object in list){
				var user:MicroBlogUser;
				if(item is MicroBlogStatus){
					user = MicroBlogStatus(item).user;
				}else
				if(item is MicroBlogComment){
					user = MicroBlogComment(item).user;
				}else
				if(item is MicroBlogDirectMessage){
					user = MicroBlogDirectMessage(item).sender;
				}
				
				//判断是否为自己，只要有一个不是自己的，则表明不是自己的
				if(user && user.id != mainData.currentUser.id){
					return true;
				}
			}
			
			return false;
		}		
		
		
		[Bindable]
		public function get mainData():MainData
		{
			return _mainData
		}
		
		public function set mainData(value:MainData):void
		{
			_mainData = value;
		}
		
		public function setItem(key:String,value:Object):void{
			sharedObject.data[key] = value;
		}
		
		//保存本地共享配置
		public function saveSharedObject():void{
			sharedObject.flush();
		}
		
		public function getSharedObject():SharedObject{
			return sharedObject;
		}
		
		//如果没有取到值，则设置为缺少值defValue(第一次运行的情况)
		public function getItem(key:String,defValue:Object):Object{
			var r:Object = sharedObject.data[key]; 
			return r!=null?r:defValue;
		}		
		
		//查看用户信息
		public function viewUserInfo(user:MicroBlogUser):void{
			mainData.shownUser = user;
			loadUserStatus(user);
			//如果不是当前用户，检查一下双方关系
			if(user.id != mainData.currentUser.id){
				trace("检查 "+user.screenName+" 和 "+mainData.currentUser.screenName +" 之间的关系");
				microBlogAPI.checkIsFollowing(user.id,null,mainData.currentUser.id,null);
			}
		}
		
		public function get isPaging():Boolean{
			return this._isPaging;
		}
		
		public function set isPaging(value:Boolean){
			this._isPaging = value;
			this.refreshPaused = _isPaging;
			/**
			//启动恢复自动刷新倒计时，
			if(!timerAutoRefresh && _isPaging){
				timerAutoRefresh = new Timer(RESTORE_REFRESH_INTERVAL*MINUTE,1);//执行一次
				timerAutoRefresh.addEventListener(TimerEvent.TIMER,startRestoreAutoRefreshHandler);
				timerAutoRefresh.addEventListener(TimerEvent.TIMER_COMPLETE,startRestoreAutoRefreshHandler);
			}
			//翻页时启动计时器
			if(_isPaging){
				timerAutoRefresh.reset();//先复位，重新计时
				timerAutoRefresh.start();
				trace("start pause auto refresh.");
			}
			 * */
		}
		
		/**
		//通知重新开始自动刷新
		private function startRestoreAutoRefreshHandler(event:TimerEvent):void{
			switch(event.type){
				case TimerEvent.TIMER:
					trace("begin pause auto refresh,and countdown starting...");
					break;
				case TimerEvent.TIMER_COMPLETE:
					trace("countdown complete,start auto refresh...");
					this.dispatchEvent(new ClientEvent(ClientEvent.RESTORE_AUTO_REFRESH));
					break;
			}
			
		}
		 * */
		 
		public function getAppPosition():Point{
			return new Point(app.nativeWindow.x,app.nativeWindow.y);
		}
		
		//注销
		public function logout():void{
			_mainData.reset();
			microBlogAPI.logout();
		}
	}
}